package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.R;
import com.gaohe.pojo.Notice;
import com.gaohe.service.NoticeService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("notice")
public class NoticeController {
    @Autowired
    NoticeService noticeService;

    @Autowired
    RedisTemplate redisTemplate;
    @GetMapping("/page")
    private R page(@RequestParam Integer page, @RequestParam Integer pageSize, @RequestParam(required = false) String name)
    {
        Page<Notice>page1 = new Page<>(page,pageSize);
        LambdaQueryWrapper<Notice>lwq = new LambdaQueryWrapper<>();
        lwq.like(!StringUtils.isEmpty(name),Notice::getTitle,name);
        lwq.orderByDesc(Notice::getUpdateTime);
        return R.success(noticeService.page(page1,lwq));
    }
//    查询全部
    @GetMapping
    private R getAll()
    {
        List<Notice> list = noticeService.list();
        return R.success(list);
    }
//  获取信息
    @GetMapping("{id}")
    private R getById(@PathVariable Long id)
    {
        Notice notice = noticeService.getById(id);
        return R.success(notice);
    }
//    更新数据
    @PutMapping
    private R update(@RequestBody Notice notice)
    {
        notice.setUpdateTime(LocalDateTime.now());
        boolean b = noticeService.updateById(notice);
        return b?R.success("更新成功"):R.error("更新失败");
    }

//    删除通知
    @DeleteMapping
    private R deleted(Long id)
    {
        return noticeService.removeById(id)?R.success("删除成功"):R.error("删除失败");
    }

//    添加数据
    @PostMapping
    private R save(@RequestBody Notice notice, HttpSession httpSession)
    {
        notice.setCreateTime(LocalDateTime.now());
        notice.setUpdateTime(LocalDateTime.now());
        Long user = (Long)redisTemplate.opsForValue().get("auth");
//        Long user = (Long)httpSession.getAttribute("user")
        notice.setUpdateUser(user);
        notice.setCreateUser(user);
        boolean flag = noticeService.save(notice);
        return flag?R.success("添加成功"):R.error("添加失败");
    }
}
